import React, { useState, useContext, useEffect } from 'react'
import classes from './Cart.module.css'

import CartDetails from './CartDetails/CartDetails.js';
import CheckOut from './CheckOut/CheckOut.js';


import CartContext from '../../store/cart-context.js'

import imgIcon from '../../asset/tacos.png'


const Cart = () => {

	console.log('Cart')
	const cartCtx = useContext(CartContext);
	const totalPrice = cartCtx.totalPrice;


	// Adding a state to control the CartDetails shown and hidden
	const [showDetails, setShowDetails] = useState(false);
	// Adding a state to control the CheckOut shown and hidden
	const [showCheckOut, setShowCheckOut] = useState(false);



	// Handler function to show/hide CartDetails
	const totalDetailsHandler = () => {
		if (totalPrice === 0) {
			setShowDetails(false);
			return;
		}
		setShowDetails(prevState => !prevState);
	}

	// Handler function to show/hide CheckOut
	const showCheckoutHandler = (e) => {
		e.stopPropagation()
		if (totalPrice === 0) return;
		setShowCheckOut(true);
	}

	const closeCheckoutHandler = (e) => {
		setShowCheckOut(false);
	}


	// By default, the function in useEffect(), will be called after the component has finished rendering, and is called every time the rendering finishes

	// Then useEffect() can be passed an array as the second parameter,
	//the useEffect() function will only be re - executed when the variables in the array change
	useEffect(() => {
		if (totalPrice === 0) {
			setShowDetails(false);
			setShowCheckOut(false);
		}
	}, [totalPrice, showDetails, showCheckOut] )


	return (
		<div
			className={classes.cartBox}
			onClick={totalDetailsHandler}
		>

			{showCheckOut && <CheckOut onClose={closeCheckoutHandler} />}

			{showDetails && <CartDetails />}

			<div className={classes.IconBox}>
				<img src={imgIcon} className={classes.IconImg} alt="cart" />
				{totalPrice !== 0 ? <div className={classes.IconText}>{cartCtx.totalAmount}</div> : null}
			</div>

			<div className={classes.AmountBox}  >

				{totalPrice !== 0 ?
					<p className={classes.Amount}>{totalPrice.toFixed(2)}</p>
					:
					<p className={classes.NoMeal}>Your cart is empty</p>
				}
			</div>

			<button
				type="button"
				class="btn btn-default"
				className={`${classes.Button} ${!(totalPrice) && classes.Disabled}`}
				onClick={showCheckoutHandler}
			>
				CheckOut
			</button>
		</div >
	)
}

export default Cart